using System;
using System.Web;
using Edge.Common.ComponentModel.Notification;
using Edge.Common.ComponentModel.Notification;

namespace Edge.Common.Web.Notification
{
    public class NotificationManager : INotificationManager
    {
        private string LISTENER_KEY;

        public NotificationManager()
        {
            LISTENER_KEY = "Dune.Common.Web.Notification.NotificationManager.LISTENER_KEY";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="listener"></param>
        public void RegisterListener(INotificationListener listener)
        {
            HttpContext httpContext = HttpContext.Current;
            if (httpContext == null)
                throw new InvalidOperationException();
            httpContext.Items[LISTENER_KEY] = listener;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        public void Notify(string msg)
        {
            GetListener(true).Notify(msg);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        public void Error(string msg)
        {
            GetListener(true).Error(msg); ;
        }

        protected INotificationListener GetListener(bool raiseErrorIfNotExists)
        {
            HttpContext httpContext = HttpContext.Current;
            if (httpContext == null)
                throw new InvalidOperationException();

            INotificationListener ret =
                (INotificationListener)httpContext.Items[LISTENER_KEY];

            if (ret == null && raiseErrorIfNotExists)
                throw new InvalidOperationException("listener does not assigned");

            return ret;
        }

    }
}